<?php
namespace Index\Controller;
class UserController extends  WxOauthController {
	
    public function  index()
	{
	  
	   $this->user=M('user')->where(array('uid'=>$_SESSION['user_info']['uid']))->find();
	   
	   $this->slide=M('slide')->where(array('ztype'=>'s1'))->order('sort desc')->limit('1')->select(); 
	  
       $this->display();
	  
	}
 
	/**
	 * 
	 * 
	 * 我的积分
	 * 
	 */
	public function mypoint(){
	    
	    
	    $this->mypoint=M('user')->field('upoint')->where(array('uid'=>$_SESSION['user_info']['uid']))->find();
	    
	    $this->slide=M('slide')->where(array('ztype'=>'s2'))->order('sort desc')->limit('1')->select(); 
	    
	    $this->display();
	}
	
	
	/**
	 * 
	 * 我的积分明细
	 * 
	 */
	public function mypointdetail(){ 
	   $this->user=M('user')->where(array('uid'=>$_SESSION['user_info']['uid']))->find();
	   $uid = $_SESSION['user_info']['uid'];
	   $cent = trim(I('cent'));
	   if (!empty($cent)) 
	   {
	   		$this ->fenji($uid,$cent);
	   }
	   else
	   {
	   		$m = new \Think\Model;
	   		$list = $m -> query("select *  from y_upoint_log where user_id = \"$uid\" order by update_time desc limit 60");
	   		$num = $m -> query("select upoint  from y_user where uid = \"$uid\"");
	   		$this -> assign('num',$num);
	   		$this -> assign('list',$list);
	   		$this->display();
	   }
	   
	}
	// 积分明细接口
	public function jifen(){
		$type = I('cent');
		$user_id = $_SESSION['user_info']['uid'];
		if(!$user_id) $this->ajaxReturn(['code'=>0,'data'=>'','msg'=>'请登录']);
		$data = $this->fenji($user_id,$type);
		$this->ajaxReturn(['code'=>200,'data'=>$data,'msg'=>'ok']);
		
	}
	
	public function fenji($uid,$cent)
	{
			$m = new \Think\Model;
				$where = array(
					'user_id'=>$uid,
				);
				if($cent){
					$where['type'] = $cent;
				}
	
			$list = M('upoint_log')->where($where)->select();
			   return $list;
	   		// $num = $m -> query("select upoint  from y_user where uid = \"$uid\"");
	   		// $this -> assign('num',$num);
	   		// $this -> assign('list',$list);
	   		// $this->display('User_mypointdetail');
	}

   /**
    * 
    * 积分商城
    * 
    */	 
	public function  goods(){
		$m = new \Think\Model;
	    $sort_info = $m -> query('select * from y_sort');
	
	    	$goods_arr=M('goods_to_sort')->order('gid desc')->select();
	    	$this -> assign('sort_info',$sort_info);
	    	$this->goods=$goods_arr;
	    
	    	$this->display(); 
	    
	}
	
	public function sort()
	{
		$sort_id = trim(I('get.sort_id'));
		if (empty($sort_id)) 
		{
			$this -> goods();
		}
		else
		{
			$goods_arr=M('goods_to_sort') -> where(array('sort_id'=>$sort_id)) ->order('gid desc')->select();
	    	$this -> ajaxReturn($goods_arr);
		}
	}


	/**
	 * 
	 * 兑换商品
	 * 
	 * 
	 */
	public function handle_goods(){
	    
	  $act=I('post.act');
	  if($act=='add')
	  {
	     $gid=I('post.gid');
	     $num=I('post.num');
	     //$this -> ajaxReturn($num);

	     
	     if(!empty($gid)){
	         
	        $g_arr=M('goods')->where(array('gid'=>$gid))->find();
	        
	        $upoint_arr=M('user')->field('upoint')->where(array('uid'=>$_SESSION['user_info']['uid']))->find();
	        $gpoint = $g_arr['gpoint'] * $num;
	        intval($gpoint>intval($upoint_arr['upoint']))?message(2,L('_NO_POINT_')):'';
	           
	        $db_arr=array(
	          'grpics'=>$g_arr['pics'],  
	          'grname'=>$g_arr['gname'],  
	          'grpoint'=>$gpoint, 
	          'gid'=>$g_arr['gid'],
	          'num'=>$num,
	          'uid'=>$_SESSION['user_info']['uid'],
	          'grtime'=>time(),  
	        ); 
	        
	        $lastId=M('goods_rec')->add($db_arr);
	        $new_upoint = $upoint_arr['upoint']-$gpoint;
	        $data = [
	        			'type' => 'less',
	        			'user_id' => $_SESSION['user_info']['uid'],
	        			'add_name' =>'购买物品',
	        			'note' => '购买'.$g_arr['gname'].'&nbsp;&nbsp;'.$num.'个',
	        			'upoint_add' => $gpoint,
	        			'upoint_old' => $upoint_arr['upoint'],
	        			'upoint_new' => $new_upoint,
	        			'update_time' => time(),
	        			'change_id' => $_SESSION['user_info']['uid']
	        		];
	        $add=M('upoint_log')->add($data);
	        if(!empty($lastId)){
	           
	            $uId=M('user')->where(array('uid'=>$_SESSION['user_info']['uid']))->setDec('upoint',$gpoint);
	            
	            !empty($uId)?message(1,L('_DO_SUCCEED_'),U('User/index')):'';
	            
	        }else{
	            
	            M('goods_rec')->where(array('grid'=>$lastId))->delete();
	        }
	      
	     }
	     
	  }
	    
	  message(2,L('_DO_FAILED_'));  
	}
	
	
	/**
	 * 
	 * 兑换积分明细
	 * 
	 */
	public function exchange(){
	    
	    $goods_arr=M('goods_rec')->where(array('uid'=>$_SESSION['user_info']['uid']))->order('gid desc')->select();
	    
	    $this->goods=$goods_arr;
	    
	    $this->display();
	}
	
 
	 
	/**
	 * 
	 * 积分排行榜
	 * 
	 * 
	 */
	public function allrank()
	{
		$bid = $_SESSION['user_info']['branch_id'];
		$uid = $_SESSION['user_info']['uid'];
		$branch_id = trim(I('get.branch_id'));
		$moth = trim(I('get.moth'));
		$desc = trim(I('get.desc'));
		$moth = empty($moth)?"year":$moth;
		$desc = empty($desc)?"desc":$desc;
		//$year = trim(I('get.year'));
		$m = new \Think\Model;
		 /*公司周排行*/
		$where = $branch_id?'where shao.branch_id='."{$bid}":"";
		if($moth == "year"){
			$list = $m->query("select y_user.uid,shao.`sum`,y_user.realname,y_user.mobile,`y_user`.`branch_id`,`shao`.`update_time` from y_user left join (select `y_upoint_log`.`user_id` AS `user_id`,sum(`y_upoint_log`.`upoint_add`) AS `sum`,`y_user`.`realname` AS `realname`,`y_user`.`mobile` AS `mobile`,`y_user`.`branch_id` AS `branch_id`,`y_upoint_log`.`update_time` AS `update_time` from (`y_upoint_log` join `y_user` on((`y_user`.`uid` = `y_upoint_log`.`user_id`))) where ((`y_upoint_log`.`type` = 'add') and (date_format(from_unixtime(`y_upoint_log`.`update_time`),'%Y-%m-%d') > DATE_SUB(CURDATE(), INTERVAL 1 YEAR))) group by `y_user`.`uid`) as shao on y_user.uid = shao.user_id"." {$where} order by sum $desc");
		}elseif($moth == "moth"){
			$list = $m->query("select y_user.uid,shao.`sum`,y_user.realname,y_user.mobile,`y_user`.`branch_id`,`shao`.`update_time` from y_user left join(select `y_upoint_log`.`user_id` AS `user_id`,sum(`y_upoint_log`.`upoint_add`) AS `sum`,`y_user`.`realname` AS `realname`,`y_user`.`mobile` AS `mobile`,`y_user`.`branch_id` AS `branch_id`,`y_upoint_log`.`update_time` AS `update_time` from (`y_upoint_log` join `y_user` on((`y_user`.`uid` = `y_upoint_log`.`user_id`))) where ((`y_upoint_log`.`type` = 'add') and (date_format(from_unixtime(`y_upoint_log`.`update_time`),'%Y-%m-%d') > (curdate() - interval 1 month)))group by `y_user`.`uid`) as shao on y_user.uid = shao.user_id" ." {$where} order by sum $desc");
		}else{
			$list = $m->query("select y_user.uid,shao.`sum`,y_user.realname,y_user.mobile,`y_user`.`branch_id`,`shao`.`update_time` from y_user 
				left join (select `y_upoint_log`.`user_id` AS `user_id`,sum(`y_upoint_log`.`upoint_add`) AS `sum`,`y_user`.`realname` AS `realname`,`y_user`.`mobile` AS `mobile`,`y_user`.`branch_id` AS `branch_id`,`y_upoint_log`.`update_time` AS `update_time`from (`y_upoint_log` join `y_user` on((`y_user`.`uid` = `y_upoint_log`.`user_id`))) where ((`y_upoint_log`.`type` = 'add') and (date_format(from_unixtime(`y_upoint_log`.`update_time`),'%Y-%m-%d') > (curdate() - interval 1 week)))group by `y_user`.`uid`) as shao on y_user.uid = shao.user_id" ." {$where} order by sum $desc");
		}
		$num = $m-> query("select sum(upoint_add) as sum from y_upoint_log where user_id=\"$uid\" and type='add'");
		$ci = $num[0]['sum'];
		$this -> assign('ci',$ci);		//总分
		$this -> assign('list',$list);	//列表
		$this -> assign('bid',$bid);	//部门ID
		$this -> assign('branch_id',$branch_id);
		$this -> assign('uid',$uid);	//用户ID
		$this -> assign('moth',$moth);	//年月周
		$this -> assign('desc',$desc);	//排序
		$this -> display();
	}
	// 积分排行接口
	public function allrank_ajax(){
		$bid = $_SESSION['user_info']['branch_id'];
		$uid = $_SESSION['user_info']['uid'];
		$branch_id = trim(I('post.branch_id'));
		$moth = trim(I('post.moth'));
		$desc = trim(I('post.desc'));
		$moth = empty($moth)?"year":$moth;
		$desc = empty($desc)?"desc":$desc;
		//$year = trim(I('get.year'));
		$m = new \Think\Model;
		 /*公司周排行*/
		$where = $branch_id?'where shao.branch_id='."{$bid}":"";
		if($moth == "year"){
			$list = $m->query("select y_user.uid,shao.`sum`,y_user.realname,y_user.mobile,`y_user`.`branch_id`,`shao`.`update_time` from y_user left join (select `y_upoint_log`.`user_id` AS `user_id`,sum(`y_upoint_log`.`upoint_add`) AS `sum`,`y_user`.`realname` AS `realname`,`y_user`.`mobile` AS `mobile`,`y_user`.`branch_id` AS `branch_id`,`y_upoint_log`.`update_time` AS `update_time` from (`y_upoint_log` join `y_user` on((`y_user`.`uid` = `y_upoint_log`.`user_id`))) where ((`y_upoint_log`.`type` = 'add') and (date_format(from_unixtime(`y_upoint_log`.`update_time`),'%Y-%m-%d') > DATE_SUB(CURDATE(), INTERVAL 1 YEAR))) group by `y_user`.`uid`) as shao on y_user.uid = shao.user_id"." {$where} order by sum $desc");
		}elseif($moth == "moth"){
			$list = $m->query("select y_user.uid,shao.`sum`,y_user.realname,y_user.mobile,`y_user`.`branch_id`,`shao`.`update_time` from y_user left join(select `y_upoint_log`.`user_id` AS `user_id`,sum(`y_upoint_log`.`upoint_add`) AS `sum`,`y_user`.`realname` AS `realname`,`y_user`.`mobile` AS `mobile`,`y_user`.`branch_id` AS `branch_id`,`y_upoint_log`.`update_time` AS `update_time` from (`y_upoint_log` join `y_user` on((`y_user`.`uid` = `y_upoint_log`.`user_id`))) where ((`y_upoint_log`.`type` = 'add') and (date_format(from_unixtime(`y_upoint_log`.`update_time`),'%Y-%m-%d') > (curdate() - interval 1 month)))group by `y_user`.`uid`) as shao on y_user.uid = shao.user_id" ." {$where} order by sum $desc");
		}else{
			$list = $m->query("select y_user.uid,shao.`sum`,y_user.realname,y_user.mobile,`y_user`.`branch_id`,`shao`.`update_time` from y_user 
				left join (select `y_upoint_log`.`user_id` AS `user_id`,sum(`y_upoint_log`.`upoint_add`) AS `sum`,`y_user`.`realname` AS `realname`,`y_user`.`mobile` AS `mobile`,`y_user`.`branch_id` AS `branch_id`,`y_upoint_log`.`update_time` AS `update_time`from (`y_upoint_log` join `y_user` on((`y_user`.`uid` = `y_upoint_log`.`user_id`))) where ((`y_upoint_log`.`type` = 'add') and (date_format(from_unixtime(`y_upoint_log`.`update_time`),'%Y-%m-%d') > (curdate() - interval 1 week)))group by `y_user`.`uid`) as shao on y_user.uid = shao.user_id" ." {$where} order by sum $desc");
		}
		$num = $m-> query("select sum(upoint_add) as sum from y_upoint_log where user_id=\"$uid\" and type='add'");
		$ci = $num[0]['sum'];

		$data = array(
			'list'=>$list,
			'ci'=>$ci,
			'bid'=>$bid,
			'branch_id'=>$branch_id,
			'uid'=>$uid,
			'moth'=>$moth，
		);
		$data['desc']=$desc;
		$this -> ajaxReturn(['code'=>200,'data'=>$data,'msg'=>'ok']);
		



	}

	
	/**
	 * 
	 * 修改密码
	 * 
	 */
	public function upwd(){
	    
	    
	    $act=I('post.act');
	    
	    if($act=='add'){
	        
	        $opwd=I('post.opwd');
	        $npwd=I('post.npwd');
	        $okpwd=I('post.okpwd');
	        
	        !is_empty($opwd,$npwd,$okpwd)?message(2,L('_IS_EMPTY_')):'';
	        
	        $npwd!==$okpwd?message(2,L('_NEQ_PWD_')):'';
	        
	        $is_exist=M('user')->where(array('mobile'=>$_SESSION['user_info']['mobile'],'upwd'=>md5($opwd.C('SALT'))))->find();
	        
	        empty($is_exist)?message(2,L('_ERR_OLDPWD_')):'';
	        
	        $eId=M('user')->where(array('mobile'=>$_SESSION['user_info']['mobile'],'upwd'=>md5($opwd.C('SALT'))))->save(array('upwd'=>md5($npwd.C('SALT'))));
	        
	        
	        
	        if(!empty($eId)){
	            
	            
	            unset($_SESSION['user_info']);
	            
	            message(1,L('_DO_SUCCEED_'),U('User/index'));
	            
	        }
	        message(2,L('_DO_FAILED_'));
	    }
	    
	    $this->display();
	}

	/**
	 * 个人设置
	 * [Ucontroller description]
	 */
	public function uc()
	{
		$this->user=M('user')->where(array('uid'=>$_SESSION['user_info']['uid']))->find();
		$uid = $_SESSION['user_info']['uid'];
		$this -> assign('uid',$uid);
		$uinfo = M('user')->where(array('uid'=>$uid))->find();
		$this -> assign('uinfo',$uinfo);
		$this -> display();
	}
	/**
	 * 显示个人基本信息
	 * [info description]
	 * @return [type] [description]
	 */
	public function info()
	{
		$uid = $_SESSION['user_info']['uid'];
		$uinfo = M('user')->where(array('uid'=>$uid))->find();
		$this -> assign('uinfo',$uinfo);
		$this -> display();
	}
	/**
	 * 修改个人基本信息
	 * [change_info description]
	 * @return [type] [description]
	 */
	public function change_info()
	{
		$realname = trim(I('realname'));
		$mobile = trim(I('mobile'));
		$sex = trim(I('sex'));
		$birthday = trim(I('birthday'));
		$uid = trim(I('uid'));
		if(empty($realname)){
			$this -> ajaxReturn ('姓名不可为空！');
		}
		if(empty($mobile)){
			$this -> ajaxReturn('电话号码不能为空!');
		}elseif(!preg_match("/^1[34578]{1}\d{9}$/", $mobile)){
			$this -> ajaxReturn('电话号码格式错误!');
		}
		$sex = in_array($sex,[0,1])?$sex:0;
		$m = new \Think\Model;
		$m -> execute("update y_user set realname=\"$realname\" , mobile=\"$mobile\" , sex=$sex , birthday=\"$birthday\" where uid = \"$uid\"");
		$this -> ajaxReturn ('修改成功');
	}


	public function forget()
	{
		$uid = trim(I('uid'));
		if (!empty($uid)) 
		{
			$m = new \Think\Model;
			$num = $m -> query("select create_time from y_forget where user_id=\"$uid\"");
			$create_time = $num[0]['create_time'];
			$time = time();
			if (empty($create_time)) 
			{
				$m -> execute("insert into y_forget(user_id,create_time) values (\"$uid\",\"$time\")");
				$this -> redirect('User/uc');
			}
			else
			{
				$today = mktime(0,0,0 , date('m') , date('d')+1 , date('Y'));
				if ($create_time < $today) 
				{
					$this -> redirect('User/uc');
				}
				else
				{
					$m -> execute("insert into y_forget(user_id,create_time) values (\"$uid\",\"$time\")");
					$this -> redirect('User/uc');
				}
			}
		}
	}

	public function login_out()
	{
		unset($_SESSION);
		session_destroy(); 
		$this -> redirect('index/index');
	}

}